import ftclient
from authorization.clientlogin import ClientLogin
from sql.sqlbuilder import SQL
import StringIO, csv
username = 'osu.map@gmail.com'
password = 'dlzosumap'
  
token = ClientLogin().authorize(username, password)
ft_client = ftclient.ClientLoginFTClient(token)

results = ft_client.query(SQL().showTables())
print results






def processResponse(text):
    import csv, StringIO
    t = StringIO.StringIO(text)
    reader = csv.reader(t)
    results = []
    h = reader.next()
    
    for l in reader:
        results.append(dict(zip(h,l)))
    t.close()
    return results
    
    

'''
print processResponse(results)
results = ft_client.query(SQL().describeTable(420692))
print results
print processResponse(results)
tableid = 422606
print processResponse(ft_client.query('select * from 422606 OFFSET 0 LIMIT 2'))

print processResponse(ft_client.query('select COUNT() as count from 422606'))
print processResponse(ft_client.query('select project_name, COUNT() as count from %s where date_<=%s GROUP BY project_name' % (423203, 2011)))

'''
USERNAME = 'osu.map@gmail.com'
PASSWORD = 'dlzosumap'
def getFtClient(username, password):
    '''get the Fusion Table Client for query'''
    token = ClientLogin().authorize(username, password)
    ft_client = ftclient.ClientLoginFTClient(token)
    return ft_client

def getMapping():
    MAPPING_TABLE = 'mapping'
    ft_client = getFtClient(USERNAME, PASSWORD)
    tables = processResponse(ft_client.query(SQL().showTables()))
    ids = [x['table id'] for x in tables if x['name']=='mapping']
    if len(ids)==1:
        tableid = ids[0]
    print tableid
    return processResponse(ft_client.query("select * from %s" % tableid))

print getMapping()
